package com.weixin.web;

import com.weixin.pojo.AccessToken;
import com.weixin.util.WXUserUtil;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping(value = "weixin/customer")
@Controller
@Slf4j
public class CustomerController {


    @RequestMapping("/to_forward")
    public String to_list(@RequestParam("code") String code, @RequestParam("state") String state, Model model,
                          HttpServletRequest request, HttpServletResponse response){
        String userId = WXUserUtil.findCookie(request);
        if("".equals(userId)) {
            AccessToken accessToken = WXUtil.getAccessToken(WxepConstants.CorpId, WxepConstants.CUSTOMER_SECRET);
            log.info("accessToken is {}", accessToken.toString());
            if (accessToken != null) {
                if (accessToken.getExpiresTime() - System.currentTimeMillis() > 0) {
                    try {
                        userId = WXUserUtil.getUserInfo(accessToken.getToken(), code);
                        log.info("com.weixin.web.WXController.toRepair code is {}, userId is {}", code, userId);
                        model.addAttribute("userId", userId);
                        Cookie cookie = new Cookie("userId",userId);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    } catch (Exception e) {
                        log.error("WXUserUtil.getUserInfo error |", e);
                    }
                }
            }
        }
        if("list".equals(state)){
            return "forward:/weixin/allocation/to_allocation";
        }if("notify".equals(state)){
            return "forward:/weixin/allocation/to_allocation?notify=1";
        }
        return "";
    }

}
